<?php

namespace App\Services;

use App\Models\ActiveApply;
use App\Models\ActiveType;
use App\Models\Active;
use common\enum\ActiveEnum;
use common\utils\SysCode;
use Illuminate\Support\Facades\DB;

class ActiveService
{

    public static function addApply($params)
    {
        if(!isset($params['active_id'])) error_exit(SysCode::FAILED);
        if(!self::checkActiveStatus($params['active_id'])) error_exit(SysCode::ACTIVE_STATUS_ERROR);
        $result = ActiveApply::insert($params);
        if(!$result) error_exit(SysCode::FAILED);
    }

    public static function checkActiveStatus($id)
    {
        $active = Active::where('id', $id)
            ->where('status', 1)
            ->where('begin_time', '<', date("Y-m-d H:i:s"))
            ->where('end_time', '>', date("Y-m-d H:i:s"))
            ->first();
        return $active;
    }

    /**
     * 获取优惠类型列表信息
     */
    public static function getTypes()
    {
        $types = ActiveType::select('id', 'name')
            ->where("status", 1)
            ->orderBy("sort", "desc")
            ->orderBy("id", "desc")
            ->get();
        return $types;

    }

    /**
     * 获取优惠信息
     */
    public static function getActive($params, $select = '*')
    {
        $where[] = ["active.status", 1];
        $where[] = ["begin_time", "<",  date("Y-m-d H:i:s")];
        $where[] = ["end_time", ">",  date("Y-m-d H:i:s")];
        if(isset($params['id']) && $id = $params['id']){
            $where[] = ["active.id", $id];
        }
        //优惠活动类型
        if(isset($params['type_id']) && $typeId = $params['type_id']){
            $where[] = ["type_id", $typeId];
        }
        $data = Active::select($select,"t.name as active_type")
            ->where($where)
            ->leftJoin("active_type as t", "t.id", "=", "active.type_id")
            ->get()
            ->toArray();
        return $data;
    }


}
